package com.example;

public class MyRunnable2 implements Runnable {
    private Counter counter;

    public MyRunnable2(Counter counter) {  // 手动添加构造函数
        this.counter = counter;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            counter.increment();  // 调用同步方法
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread thread1 = new Thread(new MyRunnable2(counter));
        Thread thread2 = new Thread(new MyRunnable2(counter));

        thread1.start();
        thread2.start();

        thread1.join();  // 等待线程1结束
        thread2.join();  // 等待线程2结束

        System.out.println("Total count: " + counter.getCount());  // 应输出2000
    }
}